<?php

namespace App\Http\Controllers;

use App\Http\Requests\StoreVideoRequest;
use App\Http\Requests\UpdateVideoRequest;
use App\Http\Resources\ServiceResource;
use App\Models\Video;
use Illuminate\Http\Request;

class VideoController extends Controller
{
    /**
     * Display a listing of the resource.
     *
     * @return \Illuminate\Http\Response
     */
    public function index(Request $request)
    {
        $per_page = $request->per_page ?? 10;

        $title = $request->title ?? '';
        $sort = json_decode($request->sort, true);

        $fields = $request->fields ?? ['id', 'title', 'description', 'link', 'hide', 'orderby', 'readnum', 'published_at'];

        $resource = Video::select($fields)->when($title, function ($query) use ($title) {
            return $query->where('title', 'like', "%$title%");
        })->when($sort, function ($query) use ($sort) {
            foreach ($sort as $item) {
                $val = str_replace('end', '', $item['order']);
                $query->orderBy($item['field'], $val);
            }
        }, function ($query) {
            return $query->orderBy('id', 'desc');
        })->paginate($per_page);

        return new ServiceResource($resource);
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  \App\Http\Requests\StoreVideoRequest  $request
     * @return \Illuminate\Http\Response
     */
    public function store(StoreVideoRequest $request, Video $video)
    {
        return $this->successful($video->create($request->all()));
    }

    /**
     * Display the specified resource.
     *
     * @param  \App\Models\Video  $video
     * @return \Illuminate\Http\Response
     */
    public function show(Video $video)
    {
        return $this->successful($video);
    }


    /**
     * Update the specified resource in storage.
     *
     * @param  \App\Http\Requests\UpdateVideoRequest  $request
     * @param  \App\Models\Video  $video
     * @return \Illuminate\Http\Response
     */
    public function update(UpdateVideoRequest $request, Video $video)
    {
        $video->update($request->all());
        return $this->successful($video);
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  \App\Models\Video  $video
     * @return \Illuminate\Http\Response
     */
    public function destroy(Video $video)
    {
        $video->delete();
        return $this->successful();
    }

    public function deleteMany(Request $request)
    {
        $ids = $request->ids;
        if (empty($ids)) {
            return $this->fail(400, 'ids is required');
        }
        Video::whereIn('id', $ids)->delete();
        return $this->successful($ids);
    }
}
